<?php
// !DESC: Method is used to authenticate a username/password for viddler.com. You must have a Viddler API Key to use this method. The method will read your variables directly from POST and look for an input with the word user in it and an input with the word pass in it. Anything else is saved to the cleaned array as is. If your form has a redirect url associated, the method will redirect the user to this URL on success, or back to your login page on failure, otherwise it just returns true or false and you can do what you want with that result.

// !LIBRARIES USED: session, phpviddler/php5viddler
// !HELPERS USED: url

// !VAR -> $api_key :: Your Viddler API KEY

function viddler_auth($api_key=NULL)
{
	
	if (is_null($api_key) || empty($api_key)) { return false; }

	$cleaned = array();
	$__ci =& get_instance();
	$__ci->load->helper('url');
	$__ci->load->library("phpviddler/php5viddler");
	$__ci->load->library("session");
		
	foreach ($_POST as $k => $v) {
		$v = strip_tags(stripslashes(trim($v)));
		if (stristr($k, "user")) {
			$cleaned['username'] = $v;
		}
		elseif (stristr($k, "pass")) {
			$cleaned['pass'] = $v;
		}
		else {
			$cleaned[$k] = $v;
		}
	}

 	$__ci->php5viddler->apiKey = $api_key;
 	$token = (isset($cleaned['token'])) ? $cleaned['token'] : NULL;
		
	try {
  		$auth = $__ci->php5viddler->user_authenticate($cleaned['username'], $cleaned['pass'], $token);
	} catch (Exception $e) {
		$__ci->session->set_userdata("login_error", $e->getMessage());
		if (isset($cleaned['redirect'])) {
			redirect(base_url() . strtolower(get_class($__ci)) . "/", "location");
  		}
  		else {
  			return false;
  		}
	}
		
	$__ci->session->unset_userdata("login_error");
	$__ci->session->set_userdata(array(
		"viddler_username"		=>		$cleaned['username'],
		"viddler_sessionid"		=>		$auth['auth']['sessionid'],
		"viddler_token"			=>		(isset($auth['auth']['record_token'])) ? $auth['auth']['record_token'] : NULL
	));
	
	if (isset($cleaned['redirect'])) {
		redirect(base_url() . $cleaned['redirect'], "location");
	}
	else {
		return true;
	}
}
?>